<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>列表参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        type="warning"
        show-icon
        class="headerInfo"
        :closable="false"
        title="注意：只允许为第三级分类设置相关参数！"
      ></el-alert>
      <!-- 选择商品分类区域 -->

      <el-row class="cat_opt">
        <!-- 选择商品分类的级联选择框 -->
        <el-col> <span>选择商品分类:</span>
          <el-cascader
            v-model="selectedCateKeys"
            :options='catelist'
            :props="cascaderProps"
            @change='handleCascaderChange'
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
      >
        <!-- 添加动态参数的面板 -->
        <el-tab-pane
          label="动态参数"
          name="many"
        >
          <!-- 添加参数的按钮 -->
          <el-button
            type="primary"
            :disabled='isBtnDisabled'
            @click='addDataDialogVisible=true'
          >添加参数</el-button>
          <!-- 动态参数列表区域 -->
          <el-table
            :data="manyTableData"
            border
            stripe
          >
            <!-- 展开列 -->
            <el-table-column
              type="expand"
              label
            >
              <template v-slot='{row}'>
                <div>
                  <el-tag
                    type="danger"
                    closable
                    v-for="(item,index) in row.attr_vals"
                    :key="index"
                    @close="deleteData(index,row)"
                  >
                    {{item}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="row.inputVisible"
                    v-model="row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(row)"
                    @blur="handleInputConfirm(row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(row)"
                  >+ New Tag</el-button>
                </div>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column
              type="index"
              label='#'
            ></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column
              label="操作"
              width="300px"
            >
              <template v-slot='{row}'>
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click='showEditDialog(row.attr_id)'
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click=deleteData(row.attr_id)
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane
          label="静态属性"
          name="only"
        >
          <!-- 添加静态属性的参数 -->
          <el-button
            type="primary"
            :disabled='isBtnDisabled'
            @click="addDataDialogVisible=true"
          >添加属性</el-button>
          <!-- 静态属性列表区域 -->
          <el-table
            :data="onlyTableData"
            border
            stripe
          >
                 <!-- 展开列 -->
            <el-table-column
              type="expand"
              label
            >
              <template v-slot='{row}'>
                <div>
                  <el-tag
                    type="danger"
                    closable
                    v-for="(item,index) in row.attr_vals"
                    :key="index"
                    @close="deleteData(index,row)"
                  >
                    {{item}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="row.inputVisible"
                    v-model="row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(row)"
                    @blur="handleInputConfirm(row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(row)"
                  >+ New Tag</el-button>
                </div>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column
              type="index"
              label='#'
            ></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column
              label="操作"
              width="300px"
            >
              <template v-slot="{row}">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click='showEditDialog(row.attr_id)'
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click=deleteData(row.attr_id)
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDataDialogVisible"
      width="50%"
      @close='closeDialog'
    >
      <el-form
        :model="addDataForm"
        ref="addDataFormRef"
        :rules="addDataFormRules"
        label-width="80px"
      >
        <el-form-item
          :label="titleText"
          prop="attr_name"
        >
          <el-input v-model="addDataForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="closeDialog">取 消</el-button>
        <el-button
          type="primary"
          @click="addData"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editDataDialogVisible"
      width="50%"
      @close='closeEditDialog'
    >
      <el-form
        :model="editDataForm"
        ref="editDataFormRef"
        :rules="editDataFormRules"
        label-width="80px"
      >
        <el-form-item
          :label="titleText"
          prop="attr_name"
        >
          <el-input v-model="editDataForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDataDialogVisible=false">取 消</el-button>
        <el-button
          type="primary"
          @click="editData(editDataForm.attr_id)"
        >确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
export default {
  props: [],
  data () {
    return {
        // ---------------------------商品列表数据-----------------

        catelist:[],
        // 级联下拉列表配置项
        cascaderProps:{
          expandTrigger:'hover',
        checkStrictly:true,
          value: 'cat_id',
          label: 'cat_name',
          children:'children'
          },
          // 级联选择框双向绑定到的数组
      selectedCateKeys: [],
      // ---------------------------tab框数据------------------------
      // 默认选中项
      activeName:'many',
      // 动态参数的数据
      manyTableData:[],
      // 静态属性的数据
      onlyTableData:[],
//  --------------------------添加功能数据-------------------
      // 控制添加对话框的开关
      addDataDialogVisible:false,
      // 添加参数的表单数据对象
       addDataForm:{
         attr_name:''
       },
      //  添加表单的验证规则对象
      addDataFormRules:{
        attr_name:[{ required: true, message:'请输入参数名称',trigger: 'blur'}]
      },
    // ------------------------编辑功能数据-------------------
editDataDialogVisible:false,
editDataForm:{},
editDataFormRules:{
        attr_name:[{ required: true, message:'请输入参数名称',trigger: 'blur'}]
},
// ----------------------tag标签数据-----------------
// //input 默认为空
// inputValue:'',
// // input默认关闭
// inputVisible:false

    }
  },
  mounted () {
      this.getCateList()
  },
  methods: {
    //   获取商品列表
  async  getCateList(){
      const { data: res } = await this.$http.get('categories')
      console.log(res);
    if(res.meta.status !== 200){return this.$message.error('获取列表失败')}
    this.catelist = res.data
    },
    // 级联选择框选中项变化，会触发这函数
    handleCascaderChange(){
      this.getParamsData()
    },
    // 获取参数的列表数据·
    async getParamsData(){
      // 证明选中的不是三级分类
      if(this.selectedCateKeys.length!==3){
           this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 证明选中的是三级分类
      // 根据所选分类的id和当前所处的面板,获取对应的参数
      this.getAttrList()
 
     
    },
    async getAttrList(){
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
          if(res.meta.status !== 200){return  this.$message.error('获取参数列表失败')}
     console.log(res);
         res.data.forEach(item=>{item.attr_vals?item.attr_vals=item.attr_vals.split(' '):[]
          //  控制文本框的显示与隐藏
      item.inputVisible = false
      // 文本框中输入的值
      item.inputValue = ''
            }
            )
          if (this.activeName === 'many') {
        this.manyTableData = res.data
         } else {
        this.onlyTableData = res.data
         }
    },
    // tab被选中时触发
    handleClick(){
         this.getAttrList()
    },
    closeDialog(){
      this.$refs.addDataFormRef.resetFields()
      this.addDataDialogVisible=false
    },
    // 添加确认
    async addData(){
      this.$refs.addDataFormRef.validate(async valid=>{
        if(!valid)return
      const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,
     {attr_name:this.addDataForm.attr_name,
      attr_sel:this.activeName,      })
      if(res.meta.status !== 201){return this.$message.error('添加参数失败')}
      this.$message.success('添加参数成功')
      this.addDataDialogVisible=false
      this.getAttrList()
      }
      )
    },
    // 编辑功能数据-------------------
    // 编辑按钮 、
  async  showEditDialog(sid){
    // 获取当前列的数据
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${sid}`,{params:{attr_sel:this.activeName}})
      console.log(res);
      this.editDataForm.attr_name=res.data.attr_name
      this.editDataForm.attr_id=res.data.attr_id
      this.editDataDialogVisible=true
      
    },
    // 对话框关闭回调
    closeEditDialog(){
      this.$refs.editDataFormRef.resetFields()
    },

  // 编辑确认
  async editData(attr_id){
    this.$refs.editDataFormRef.validate(async valid=>{
      if(!valid){return}
    const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${attr_id}`,{
      attr_name:this.editDataForm.attr_name,
      attr_sel:this.activeName})
      console.log(res);
    if(res.meta.status !== 200){return this.$message.error('获取参数失败')}
    this.editDataForm=res.data
    this.getAttrList()
    this.editDataDialogVisible=false
    })
  },
  // 删除功能-------------------
 deleteData(attr_id){
  this.$confirm('确认删除?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    callback:async action => {
      if(action === 'confirm'){
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
        // console.log(res);
        if(res.meta.status !== 200){return this.$message.error('删除失败')}
        this.$message.success('删除成功')
        this.getAttrList()

      }else{
        this.$message.info('取消删除')
      }
    }
  })
  
},
   // 关闭input框的回调
   async handleInputConfirm(row){
    //  如果输入的值为空
     if(row.inputValue.trim().length===0){
       row.inputVisible = false;
      row.inputValue = '';
      return
     }
    //  如果输入的值不为空，
    // 发送请求把添加的数据更新
    // 先保存到本地保证页面的事实更新
    row.attr_vals.push(row.inputValue.trim())
     row.inputVisible = false;
      row.inputValue = '';
    const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
      attr_name:row.attr_name,
      attr_sel:row.attr_sel,
      // 数据库存储的是字符串类型的参数，还需要把数组转化为字符串
      attr_vals:row.attr_vals.join(' ')
    } )
  // console.log(res);
  if(res.meta.status !== 200){return this.$message.error('修改参数项失败')}
  this.$message.success('修改参数项成功')
    },
    // 显示input触发的函数
    showInput(row){
      // console.log(row);
       row.inputVisible = true;
         this.$nextTick(_ => {
          //  console.log(this);‘
          // 自动获取焦点
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    // tag删除事件
     deleteData(index,row){

      this.$confirm('确认删除?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        callback: async action=> {
          if(action === 'confirm'){
            row.attr_vals.splice(index,1)
            const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
            // console.log(res);
          if(res.meta.status !== 200){return this.$message.error('删除失败！')}
          this.$message.success('删除成功')
          }else{
            this.$message.info('取消删除')
          }
        }
      })
    }
  },
  computed:{
    // 按钮在三级分类选中之前被禁用
    isBtnDisabled(){
      return this.selectedCateKeys<3
    },
    // 获取参数id
    cateId(){
      if(this.selectedCateKeys.length===3){
        return this.selectedCateKeys[2]
      }
    },
    titleText(){
return this.activeName==='many'?'动态参数': '静态属性'   
    },
 
  }
}
</script>
<style lang="less" scoped>
.headerInfo{
    width: 100%;
    font-size: 16px;
}
.cateSelect{
    margin-top: 15px;
   
}
.cat_opt{
  margin-top: 15px;
  
  padding: 0;
}
.el-tag{
  margin: 0 5px;
}
.el-cascader{
  margin-left: 10px;
}
.el-input{
  width: 150px;
}
</style>